package com.itheima.reggie.exeption;

import com.itheima.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExeptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handlerSQLConstraintException(Exception exception) {
        if(exception == null){
            System.out.println(exception.getMessage());
            return Result.error("数据异常");
        }

        String message = exception.getMessage();

        if(message.contains("SQLIntegrityConstraintViolationException")){
            if(message.contains("Duplicate entry")){
              String[] mesArr = message.split("Duplicate entry");
                String[] userArr = mesArr[mesArr.length - 1].split("for key");
                return Result.error("用户名"+userArr[0]+"已存在");

            }else{
                return Result.error("数据异常");
            }
        }else{
            return Result.error("数据异常");
        }

    }
}
